// API基础URL
const API_BASE_URL = '/api';

// DOM元素（将在DOMContentLoaded中初始化）
let loginSection, mainContent, loginForm, logoutBtn;
let editGoodsModal, editGoodsForm;
let closeModalBtns;

// 表格元素
let inventoryOverviewTableBody, inventoryDetailsTableBody;

// 统计元素
let totalGoodsTypes, totalInventoryQuantity, occupiedLocations, emptyLocations;

// 查询元素
let materialCode, materialName, palletId, documentId, aisle, row, column, level;
let searchBtn, resetBtn, exportBtn;

// 库存明细查询元素
let detailMaterialCode, detailPalletId, detailDocumentId, detailWarehouseArea;
let detailAisle, detailRow, detailColumn, detailLevel;
let detailSearchBtn, detailResetBtn, detailExportBtn;

// JWT令牌
let authToken = localStorage.getItem('authToken');

// 当前编辑的货物信息
let currentEditGoods = null;

// 当前库存数据
let currentInventoryData = [];

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化...');
    
    // 初始化DOM元素
    initializeDOMElements();
    
    // 检查用户是否已登录
    if (authToken) {
        showMainContent();
        loadAllData();
    } else {
        showLoginSection();
    }
    
    // 绑定事件监听器
    bindEventListeners();
});

// 初始化DOM元素
function initializeDOMElements() {
    // 认证相关元素
    loginSection = document.getElementById('loginSection');
    mainContent = document.getElementById('mainContent');
    loginForm = document.getElementById('loginForm');
    logoutBtn = document.getElementById('logoutBtn');

    // 模态框元素
    editGoodsModal = document.getElementById('editGoodsModal');
    editGoodsForm = document.getElementById('editGoodsForm');
    closeModalBtns = document.querySelectorAll('.close');

    // 表格元素
    inventoryOverviewTableBody = document.querySelector('#inventoryOverviewTable tbody');
    inventoryDetailsTableBody = document.querySelector('#inventoryDetailsTable tbody');

    // 统计元素
    totalGoodsTypes = document.getElementById('totalGoodsTypes');
    totalInventoryQuantity = document.getElementById('totalInventoryQuantity');
    occupiedLocations = document.getElementById('occupiedLocations');
    emptyLocations = document.getElementById('emptyLocations');

    // 库存总览查询元素
    materialCode = document.getElementById('materialCode');
    materialName = document.getElementById('materialName');
    palletId = document.getElementById('palletId');
    documentId = document.getElementById('documentId');
    aisle = document.getElementById('aisle');
    row = document.getElementById('row');
    column = document.getElementById('column');
    level = document.getElementById('level');
    searchBtn = document.getElementById('searchBtn');
    resetBtn = document.getElementById('resetBtn');
    exportBtn = document.getElementById('exportBtn');

    // 库存明细查询元素
    detailMaterialCode = document.getElementById('detailMaterialCode');
    detailPalletId = document.getElementById('detailPalletId');
    detailDocumentId = document.getElementById('detailDocumentId');
    detailWarehouseArea = document.getElementById('detailWarehouseArea');
    detailAisle = document.getElementById('detailAisle');
    detailRow = document.getElementById('detailRow');
    detailColumn = document.getElementById('detailColumn');
    detailLevel = document.getElementById('detailLevel');
    detailSearchBtn = document.getElementById('detailSearchBtn');
    detailResetBtn = document.getElementById('detailResetBtn');
    detailExportBtn = document.getElementById('detailExportBtn');
}

// 绑定事件监听器
function bindEventListeners() {
    console.log('开始绑定事件监听器...');
    
    // 登录表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
        console.log('已绑定登录表单提交事件');
    }
    
    // 登出按钮
    if (logoutBtn) {
        logoutBtn.addEventListener('click', handleLogout);
        console.log('已绑定登出按钮点击事件');
    }
    
    // 关闭模态框按钮
    if (closeModalBtns) {
        closeModalBtns.forEach(btn => {
            btn.addEventListener('click', closeAllModals);
        });
        console.log('已绑定关闭模态框按钮点击事件');
    }
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        const modals = [editGoodsModal];
        if (modals.includes(event.target)) {
            closeAllModals();
        }
    });
    
    // 编辑货物表单提交
    if (editGoodsForm) {
        editGoodsForm.addEventListener('submit', handleEditGoodsSubmit);
    }
    
    // 库存总览查询按钮
    if (searchBtn) {
        searchBtn.addEventListener('click', handleSearch);
    }
    
    // 库存总览重置按钮
    if (resetBtn) {
        resetBtn.addEventListener('click', handleReset);
    }
    
    // 库存总览导出按钮
    if (exportBtn) {
        exportBtn.addEventListener('click', handleExport);
    }
    
    // 库存明细查询按钮
    if (detailSearchBtn) {
        detailSearchBtn.addEventListener('click', handleDetailSearch);
    }
    
    // 库存明细重置按钮
    if (detailResetBtn) {
        detailResetBtn.addEventListener('click', handleDetailReset);
    }
    
    // 库存明细导出按钮
    if (detailExportBtn) {
        detailExportBtn.addEventListener('click', handleDetailExport);
    }
    
    // 模块导航
    setupModuleNavigation();
    
    console.log('事件监听器绑定完成');
}

// 设置模块导航
function setupModuleNavigation() {
    const navLinks = document.querySelectorAll('.module-nav a');
    const sections = document.querySelectorAll('.module-section');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有活动状态
            navLinks.forEach(l => l.classList.remove('active'));
            sections.forEach(s => s.classList.remove('active'));
            
            // 添加当前活动状态
            this.classList.add('active');
            const targetSection = document.querySelector(this.getAttribute('href'));
            if (targetSection) {
                targetSection.classList.add('active');
            }
        });
    });
}

// 显示登录界面
function showLoginSection() {
    console.log('显示登录界面');
    if (loginSection) loginSection.style.display = 'block';
    if (mainContent) mainContent.style.display = 'none';
}

// 显示主内容界面
function showMainContent() {
    console.log('显示主内容界面');
    if (loginSection) loginSection.style.display = 'none';
    if (mainContent) mainContent.style.display = 'block';
}

// 处理登录
function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    fetch(`${API_BASE_URL}/auth/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            authToken = data.data.token;
            localStorage.setItem('authToken', authToken);
            showMainContent();
            loadAllData();
        } else {
            alert('登录失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('登录失败:', error);
        alert('登录失败');
    });
}

// 处理登出
function handleLogout() {
    authToken = null;
    localStorage.removeItem('authToken');
    showLoginSection();
}

// 关闭所有模态框
function closeAllModals() {
    console.log('关闭所有模态框');
    const modals = [editGoodsModal];
    modals.forEach(modal => {
        if (modal) modal.style.display = 'none';
    });
    
    // 重置表单
    if (editGoodsForm) editGoodsForm.reset();
}

// 处理编辑货物表单提交
function handleEditGoodsSubmit(event) {
    event.preventDefault();
    
    const id = document.getElementById('editGoodsId').value;
    const goodsData = {
        name: document.getElementById('editGoodsName').value,
        sku: document.getElementById('editGoodsSku').value,
        quantity: parseFloat(document.getElementById('editGoodsQuantity').value) || 0,
        location: document.getElementById('editGoodsLocation').value,
        status: document.getElementById('editGoodsStatus').value,
        batchNumber: document.getElementById('editGoodsBatch').value,
        specification: document.getElementById('editGoodsSpecification').value,
        unit: document.getElementById('editGoodsUnit').value
    };
    
    updateGoods(id, goodsData);
}

// 处理库存总览查询
function handleSearch() {
    console.log('执行库存总览查询');
    loadInventoryData();
}

// 处理库存总览重置
function handleReset() {
    console.log('重置库存总览查询条件');
    // 重置所有查询条件
    if (materialCode) materialCode.value = '';
    if (materialName) materialName.value = '';
    if (palletId) palletId.value = '';
    if (documentId) documentId.value = '';
    if (aisle) aisle.value = '';
    if (row) row.value = '';
    if (column) column.value = '';
    if (level) level.value = '';
    
    // 重新加载所有数据
    loadInventoryData();
}

// 处理库存总览导出
function handleExport() {
    console.log('导出库存总览Excel');
    
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    // 构建查询参数
    const queryParams = new URLSearchParams();
    
    if (materialCode && materialCode.value) {
        queryParams.append('sku', materialCode.value);
    }
    
    if (materialName && materialName.value) {
        queryParams.append('name', materialName.value);
    }
    
    if (palletId && palletId.value) {
        queryParams.append('palletId', palletId.value);
    }
    
    if (documentId && documentId.value) {
        queryParams.append('documentId', documentId.value);
    }
    
    if (aisle && aisle.value) {
        queryParams.append('aisle', aisle.value);
    }
    
    if (row && row.value) {
        queryParams.append('row', row.value);
    }
    
    if (column && column.value) {
        queryParams.append('column', column.value);
    }
    
    if (level && level.value) {
        queryParams.append('level', level.value);
    }
    
    let url = `${API_BASE_URL}/goods/export/overview`;
    if (queryParams.toString()) {
        url += `?${queryParams.toString()}`;
    }
    
    // 使用fetch API下载文件
    fetch(url, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('导出失败');
        }
        return response.blob();
    })
    .then(blob => {
        // 创建下载链接
        const downloadUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = '库存总览导出.xlsx';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
    })
    .catch(error => {
        console.error('导出Excel失败:', error);
        alert('导出Excel失败: ' + error.message);
    });
}

// 处理库存明细查询
function handleDetailSearch() {
    console.log('执行库存明细查询');
    loadInventoryDetailsData();
}

// 处理库存明细重置
function handleDetailReset() {
    console.log('重置库存明细查询条件');
    // 重置所有查询条件
    if (detailMaterialCode) detailMaterialCode.value = '';
    if (detailPalletId) detailPalletId.value = '';
    if (detailDocumentId) detailDocumentId.value = '';
    if (detailWarehouseArea) detailWarehouseArea.value = '';
    if (detailAisle) detailAisle.value = '';
    if (detailRow) detailRow.value = '';
    if (detailColumn) detailColumn.value = '';
    if (detailLevel) detailLevel.value = '';
    
    // 重新加载所有数据
    loadInventoryDetailsData();
}

// 处理库存明细导出
function handleDetailExport() {
    console.log('导出库存明细Excel');
    
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    // 构建查询参数
    const queryParams = new URLSearchParams();
    
    if (detailMaterialCode && detailMaterialCode.value) {
        queryParams.append('sku', detailMaterialCode.value);
    }
    
    if (detailPalletId && detailPalletId.value) {
        queryParams.append('palletId', detailPalletId.value);
    }
    
    if (detailDocumentId && detailDocumentId.value) {
        queryParams.append('documentId', detailDocumentId.value);
    }
    
    if (detailWarehouseArea && detailWarehouseArea.value) {
        queryParams.append('warehouseArea', detailWarehouseArea.value);
    }
    
    if (detailAisle && detailAisle.value) {
        queryParams.append('aisle', detailAisle.value);
    }
    
    if (detailRow && detailRow.value) {
        queryParams.append('row', detailRow.value);
    }
    
    if (detailColumn && detailColumn.value) {
        queryParams.append('column', detailColumn.value);
    }
    
    if (detailLevel && detailLevel.value) {
        queryParams.append('level', detailLevel.value);
    }
    
    let url = `${API_BASE_URL}/goods/export/details`;
    if (queryParams.toString()) {
        url += `?${queryParams.toString()}`;
    }
    
    // 使用fetch API下载文件
    fetch(url, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('导出失败');
        }
        return response.blob();
    })
    .then(blob => {
        // 创建下载链接
        const downloadUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = '库存明细导出.xlsx';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
    })
    .catch(error => {
        console.error('导出Excel失败:', error);
        alert('导出Excel失败: ' + error.message);
    });
}

// 加载所有数据
function loadAllData() {
    loadInventoryData();
    loadInventoryDetailsData();
}

// 加载库存总览数据
function loadInventoryData() {
    if (!authToken) return;
    
    // 构建查询参数
    const queryParams = new URLSearchParams();
    
    if (materialCode && materialCode.value) {
        queryParams.append('sku', materialCode.value);
    }
    
    if (materialName && materialName.value) {
        queryParams.append('name', materialName.value);
    }
    
    if (palletId && palletId.value) {
        queryParams.append('palletId', palletId.value);
    }
    
    if (documentId && documentId.value) {
        queryParams.append('documentId', documentId.value);
    }
    
    if (aisle && aisle.value) {
        queryParams.append('aisle', aisle.value);
    }
    
    if (row && row.value) {
        queryParams.append('row', row.value);
    }
    
    if (column && column.value) {
        queryParams.append('column', column.value);
    }
    
    if (level && level.value) {
        queryParams.append('level', level.value);
    }
    
    let url = `${API_BASE_URL}/goods`;
    if (queryParams.toString()) {
        url += `?${queryParams.toString()}`;
    }
    
    fetch(url, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentInventoryData = data.data;
                renderInventoryOverviewTable(data.data);
                updateInventoryStats(data.data);
            }
        })
        .catch(error => {
            console.error('加载库存总览数据失败:', error);
        });
}

// 加载库存明细数据
function loadInventoryDetailsData() {
    if (!authToken) return;
    
    // 构建查询参数
    const queryParams = new URLSearchParams();
    
    if (detailMaterialCode && detailMaterialCode.value) {
        queryParams.append('sku', detailMaterialCode.value);
    }
    
    if (detailPalletId && detailPalletId.value) {
        queryParams.append('palletId', detailPalletId.value);
    }
    
    if (detailDocumentId && detailDocumentId.value) {
        queryParams.append('documentId', detailDocumentId.value);
    }
    
    if (detailWarehouseArea && detailWarehouseArea.value) {
        queryParams.append('warehouseArea', detailWarehouseArea.value);
    }
    
    if (detailAisle && detailAisle.value) {
        queryParams.append('aisle', detailAisle.value);
    }
    
    if (detailRow && detailRow.value) {
        queryParams.append('row', detailRow.value);
    }
    
    if (detailColumn && detailColumn.value) {
        queryParams.append('column', detailColumn.value);
    }
    
    if (detailLevel && detailLevel.value) {
        queryParams.append('level', detailLevel.value);
    }
    
    let url = `${API_BASE_URL}/goods`;
    if (queryParams.toString()) {
        url += `?${queryParams.toString()}`;
    }
    
    fetch(url, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderInventoryDetailsTable(data.data);
            }
        })
        .catch(error => {
            console.error('加载库存明细数据失败:', error);
        });
}

// 渲染库存总览表格
function renderInventoryOverviewTable(goodsList) {
    if (!inventoryOverviewTableBody) return;
    
    inventoryOverviewTableBody.innerHTML = '';
    
    goodsList.forEach(goods => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${goods.id}</td>
            <td>DOC${String(goods.id).padStart(3, '0')}</td>
            <td>${goods.sku}</td>
            <td>${goods.name}</td>
            <td>${goods.quantity}</td>
            <td>${goods.specification || '-'}</td>
            <td>${goods.unit || '件'}</td>
        `;
        inventoryOverviewTableBody.appendChild(row);
    });
    
    // 库存总览页面不添加点击事件，因此不可编辑
}

// 渲染库存明细表格
function renderInventoryDetailsTable(goodsList) {
    if (!inventoryDetailsTableBody) return;
    
    inventoryDetailsTableBody.innerHTML = '';
    
    goodsList.forEach(goods => {
        // 生成TP+5位自然数格式的托盘号
        const palletNumber = 'TP' + String(goods.id).padStart(5, '0');
        
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${goods.id}</td>
            <td>${goods.location || '-'}</td>
            <td>DOC${String(goods.id).padStart(3, '0')}</td>
            <td>${palletNumber}</td>
            <td class="sku-cell" data-id="${goods.id}">${goods.sku}</td>
            <td>${goods.name}</td>
            <td>${goods.specification || '-'}</td>
            <td>${goods.quantity}</td>
            <td>${goods.unit || '件'}</td>
            <td>${goods.created_at ? formatDate(goods.created_at) : '-'}</td>
        `;
        inventoryDetailsTableBody.appendChild(row);
    });
    
    // 为物料编码单元格添加点击事件，仅在库存明细页面可编辑
    document.querySelectorAll('.sku-cell').forEach(cell => {
        cell.addEventListener('click', function() {
            const goodsId = this.getAttribute('data-id');
            const goods = goodsList.find(item => item.id == goodsId);
            if (goods) {
                openEditGoodsModal(goods);
            }
        });
    });
}

// 更新库存统计
function updateInventoryStats(goodsList) {
    if (!totalGoodsTypes || !totalInventoryQuantity || !occupiedLocations || !emptyLocations) return;
    
    totalGoodsTypes.textContent = goodsList.length;
    
    let totalQuantity = 0;
    let occupiedCount = 0;
    let emptyCount = 0;
    
    goodsList.forEach(goods => {
        totalQuantity += goods.quantity;
        if (goods.status === 'inStock') {
            occupiedCount++;
        } else {
            emptyCount++;
        }
    });
    
    totalInventoryQuantity.textContent = totalQuantity;
    occupiedLocations.textContent = occupiedCount;
    emptyLocations.textContent = emptyCount;
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

// 打开编辑货物模态框
function openEditGoodsModal(goods) {
    console.log('打开编辑货物模态框:', goods);
    if (editGoodsModal) {
        // 填充表单数据
        document.getElementById('editGoodsId').value = goods.id;
        document.getElementById('editGoodsName').value = goods.name || '';
        document.getElementById('editGoodsSku').value = goods.sku || '';
        document.getElementById('editGoodsUnit').value = goods.unit || '';
        document.getElementById('editGoodsSpecification').value = goods.specification || '';
        document.getElementById('editGoodsQuantity').value = goods.quantity || 0;
        document.getElementById('editGoodsLocation').value = goods.location || '';
        document.getElementById('editGoodsStatus').value = goods.status || 'inStock';
        document.getElementById('editGoodsBatch').value = goods.batch_number || '';
        
        currentEditGoods = goods;
        editGoodsModal.style.display = 'block';
    }
}

// 更新货物
function updateGoods(id, goodsData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/goods/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(goodsData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('货物更新成功');
            closeAllModals();
            loadInventoryData();
            loadInventoryDetailsData();
        } else {
            alert('货物更新失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('更新货物失败:', error);
        alert('更新货物失败');
    });
}

// 删除货物
function deleteGoods(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    if (confirm('确定要删除这个货物吗？')) {
        fetch(`${API_BASE_URL}/goods/${id}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('货物删除成功');
                loadInventoryData();
                loadInventoryDetailsData();
            } else {
                alert('货物删除失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('删除货物失败:', error);
            alert('删除货物失败');
        });
    }
}